//
//  PostDetailViewController.m
//  SXHomeTownClub
//
//  Created by 周思扬 on 2018/5/29.
//  Copyright © 2018年 jsx. All rights reserved.
//

#import "PostDetailViewController.h"
#import "PostDetailData.h"
#import "PostDetailTableViewCell_header.h"
#import "PostDetailTableViewCell_sep.h"
#import "PostDetailTableViewCell_footer.h"

@interface PostDetailViewController ()<UITextFieldDelegate>
{
    BOOL hasNewData;
    BottomCommentView * bottom;
}
@property(nonatomic, assign) int currentPage;
@property(nonatomic,strong) PostDetailData * detailData;
@property(nonatomic,strong) NSMutableArray * commentList;

@end

@implementation PostDetailViewController

#pragma mark - 生命周期
- (void)addSubViews
{
    [self.tableview registerNib:[UINib nibWithNibName:@"PostDetailTableViewCell_header" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"postDetailTableViewCell_header"];
    [self.tableview registerNib:[UINib nibWithNibName:@"PostDetailTableViewCell_sep" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"postDetailTableViewCell_sep"];
    [self.tableview registerNib:[UINib nibWithNibName:@"PostDetailTableViewCell_footer" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"postDetailTableViewCell_footer"];
    
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableview.estimatedRowHeight=200;
    self.tableview.rowHeight=UITableViewAutomaticDimension;
    
    bottom=[BottomCommentView shareView];
    bottom.frame=self.bottomView.bounds;
    bottom.inputField.delegate=self;
    [[bottom.collectionBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self collectionThisPost];
    }];
    [[bottom.likeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self likeThisPost];
    }];
    [self.bottomView addSubview:bottom];
    
    self.currentPage=0;
    self.needNoNetTips=YES;
    self.needNoTableViewDataTips=YES;
    self.baseTableview=self.tableview;
}

-(void)getInitData
{
    if(self.currentPage==0)
    {
        [self getPostDetailData];
        [self getPostCommentData];
    }else
    {
        [self getPostCommentData];
    }
    
}

-(void)setNavigationBar
{
    self.title=@"文章详情";
}

-(void)reloadBottomUI
{
    if([self.detailData.zanstatus isEqualToString:@"1"])
    {
        bottom.likeBtn.selected=YES;
    }else
    {
        bottom.likeBtn.selected=NO;
    }
    
    if([self.detailData.scstatus isEqualToString:@"1"])
    {
        bottom.collectionBtn.selected=YES;
    }else
    {
        bottom.collectionBtn.selected=NO;
    }
}

#pragma mark - 接口访问

-(void)getPostDetailData
{
    [SVProgressHUD showWithStatus:@"文章加载中..."];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=self.uid;
    params[@"tid"]=self.tid;
    params[@"from_type"]=self.from_type;
    [JSXHttpTool Post:Interface_FirstPageMainDetail params:params success:^(id json) {
        NSNumber * code=json[@"code"];
        if([code intValue]==1)
        {
            [SVProgressHUD dismiss];
            self.detailData=[PostDetailData mj_objectWithKeyValues:json[@"msg"]];
            [self.tableview reloadData];
            [self reloadBottomUI];
        }else
        {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:json[@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}

-(void)getPostCommentData
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=self.uid;
    params[@"tid"]=self.tid;
    params[@"from_type"]=self.from_type;
    params[@"pl"]=@"2";
    params[@"page"]=@(self.currentPage);
    [JSXHttpTool Post:Interface_FirstPageMainDetailComment params:params success:^(id json) {
        NSNumber * code=json[@"code"];
        if([code intValue]==1)
        {
            if(self.currentPage==0)
            {
                if(self.commentList.count>0)
                {
                    [self.commentList removeAllObjects];
                }
            }
            
            self->hasNewData=YES;
            [self setMainTableViewFooterView];
            
            NSArray * msgArr=json[@"msg"];
            for(int i=0;i<msgArr.count;i++)
            {
                NSDictionary * dict=msgArr[i];
                PostDetailData * data=[PostDetailData mj_objectWithKeyValues:dict];
                [self.commentList addObject:data];
            }
            [self.tableview reloadData];
        }else if([code intValue]==0)
        {
            self->hasNewData=NO;
            [self setMainTableViewFooterView];
            if(self.currentPage>1)
            {
                self.currentPage--;
            }
        }else
        {
            if(self.currentPage>1)
            {
                self.currentPage--;
            }
        }
    } failure:^(NSError *error) {
        if(self.currentPage>1)
        {
            self.currentPage--;
        }
    }];
}

-(void)postCommentData:(NSString*)message
{
    if(message.length==0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入评论信息"];
        return;
    }
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=self.uid;
    params[@"tid"]=self.tid;
    params[@"fid"]=self.detailData.fid;
    params[@"subject"]=@"";
    params[@"message"]=message;
    [JSXHttpTool Post:Interface_FirstPageMainPostComment params:params success:^(id json) {
        NSNumber * code=json[@"code"];
        if([code intValue]==0)
        {
            self.currentPage=0;
            [self getPostCommentData];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"发送失败"];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)focusUser
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=self.uid;
    params[@"followuid"]=self.detailData.uid;
    [JSXHttpTool Post:Interface_FirstPageMainFocusUser params:params success:^(id json) {
        NSNumber * code=json[@"code"];
        if([code intValue]==1)
        {
            self.detailData.guanstatus=@"1";
            [self.tableview reloadData];
            [SVProgressHUD showSuccessWithStatus:@"关注成功"];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"操作失败"];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)likeThisPost
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=self.uid;
    params[@"tid"]=self.tid;
    [JSXHttpTool Post:Interface_FirstPageMainLikeThisPost params:params success:^(id json) {
        NSNumber * code=json[@"code"];
        if([code intValue]==1)
        {
            [self getPostDetailData];
        }else if([code intValue]==2)
        {
            [self getPostDetailData];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"操作失败"];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)collectionThisPost
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=self.uid;
    params[@"tid"]=self.tid;
    params[@"from_type"]=self.from_type;
    [JSXHttpTool Post:Interface_FirstPageMainCollectionThisPost params:params success:^(id json) {
        NSNumber * code=json[@"code"];
        if([code intValue]==1)
        {
            [self getPostDetailData];
        }else if([code intValue]==2)
        {
            [self getPostDetailData];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"操作失败"];
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - UITextField代理

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    [self postCommentData:textField.text];
    return YES;
}

#pragma mark - tableview代理数据源

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView==self.tableview)
    {
        CGFloat height = scrollView.frame.size.height;
        CGFloat contentYoffset = scrollView.contentOffset.y;
        CGFloat distance = scrollView.contentSize.height-height-contentYoffset;
        if (distance<=0&&hasNewData) {
            self.currentPage++;
            [self getInitData];
        }
    }
}

-(void)setMainTableViewFooterView
{
    if(hasNewData)
    {
        TableViewOfRefreshFooterView * footer = [TableViewOfRefreshFooterView shareView];
        footer.frame=CGRectMake(0, 0, SDScreenWidth, 60);
        self.tableview.tableFooterView=footer;
    }else
    {
        TableViewOfRefreshFooterView2 * footer2 = [TableViewOfRefreshFooterView2 shareView];
        footer2.frame=CGRectMake(0, 0, SDScreenWidth, 60);
        self.tableview.tableFooterView=footer2;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commentList.count+2;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==0)
    {
        PostDetailTableViewCell_header * cell = [tableView dequeueReusableCellWithIdentifier:@"postDetailTableViewCell_header"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.contentData=self.detailData;
        
        //点击关注
        cell.focusblock = ^{
            [self focusUser];
        };
        
        //点击头像
        cell.userblock = ^{
            SDLog(@"用户");
        };
       
        //点击图片
        cell.block = ^(int imgIndex) {
            NSMutableArray * photos=[NSMutableArray array];
            for (PostDetailData_article * article in self.detailData.wen) {
                if([article.type isEqualToString:@"IMAGE"])
                {
                    MWPhoto * photo=[[MWPhoto alloc]initWithURL:[NSURL URLWithString:article.content]];
                    [photos addObject:photo];
                }
            }
            MWPhotoBrowser * brower=[[MWPhotoBrowser alloc]initWithPhotos:photos];
            brower.displayActionButton=NO;
            [brower setCurrentPhotoIndex:imgIndex-1];
            [self.navigationController pushViewController:brower animated:YES];
        };
        return cell;
    }else if(indexPath.row==1)
    {
        PostDetailTableViewCell_sep * cell = [tableView dequeueReusableCellWithIdentifier:@"postDetailTableViewCell_sep"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }else
    {
        PostDetailTableViewCell_footer * cell = [tableView dequeueReusableCellWithIdentifier:@"postDetailTableViewCell_footer"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        PostDetailData * commentData=self.commentList[indexPath.row-2];
        cell.commentData=commentData;
        return cell;
    }
    return nil;
    
}

#pragma mark - LazyLoad

-(NSMutableArray *)commentList
{
    if(_commentList==nil)
    {
        _commentList=[NSMutableArray array];
    }
    return _commentList;
}


@end
